import { ref, reactive, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  getStructureOverview,
  getDeviceTypeDistribution,
  getDeviceStatusStats,
  getSignalQualityAnalysis,
  getTaskExecutionStats,
  getOptimizationEffectAnalysis,
  getDevicePerformanceTrend,
  getTaskTypeDistribution,
  getOptimizationSuccessRate,
  getNetworkTopology
} from '../apis/structure.js'

export const useStructureAnalysis = () => {
  // 加载状态
  const loading = ref(false)
  
  // 概览数据
  const overviewData = ref({})
  
  // 设备类型分布
  const deviceTypeDistribution = ref([])
  
  // 设备状态统计
  const deviceStatusStats = ref({})
  
  // 信号质量分析
  const signalQualityData = ref({})
  
  // 任务执行统计
  const taskExecutionStats = ref({})
  
  // 优化效果分析
  const optimizationEffectData = ref({})
  
  // 设备性能趋势
  const devicePerformanceTrend = ref({})
  
  // 任务类型分布
  const taskTypeDistribution = ref([])
  
  // 优化成功率统计
  const optimizationSuccessRate = ref({})
  
  // 网络拓扑结构
  const networkTopology = ref({})
  
  // 查询参数
  const queryParams = reactive({
    startTime: '',
    endTime: '',
    deviceType: '',
    taskType: ''
  })

  // 获取结构分析概览
  const fetchOverview = async () => {
    try {
      const response = await getStructureOverview()
      if (response.code === 200) {
        overviewData.value = response.data
      }
    } catch (error) {
      console.error('获取概览数据失败:', error)
      ElMessage.error('获取概览数据失败')
    }
  }

  // 获取设备类型分布
  const fetchDeviceTypeDistribution = async () => {
    try {
      const response = await getDeviceTypeDistribution()
      if (response.code === 200) {
        deviceTypeDistribution.value = response.data
      }
    } catch (error) {
      console.error('获取设备类型分布失败:', error)
      ElMessage.error('获取设备类型分布失败')
    }
  }

  // 获取设备状态统计
  const fetchDeviceStatusStats = async () => {
    try {
      const response = await getDeviceStatusStats()
      if (response.code === 200) {
        deviceStatusStats.value = response.data
      }
    } catch (error) {
      console.error('获取设备状态统计失败:', error)
      ElMessage.error('获取设备状态统计失败')
    }
  }

  // 获取信号质量分析
  const fetchSignalQualityAnalysis = async () => {
    try {
      const response = await getSignalQualityAnalysis(queryParams)
      if (response.code === 200) {
        signalQualityData.value = response.data
      }
    } catch (error) {
      console.error('获取信号质量分析失败:', error)
      ElMessage.error('获取信号质量分析失败')
    }
  }

  // 获取任务执行统计
  const fetchTaskExecutionStats = async () => {
    try {
      const response = await getTaskExecutionStats()
      if (response.code === 200) {
        taskExecutionStats.value = response.data
      }
    } catch (error) {
      console.error('获取任务执行统计失败:', error)
      ElMessage.error('获取任务执行统计失败')
    }
  }

  // 获取优化效果分析
  const fetchOptimizationEffectAnalysis = async () => {
    try {
      const response = await getOptimizationEffectAnalysis(queryParams)
      if (response.code === 200) {
        optimizationEffectData.value = response.data
      }
    } catch (error) {
      console.error('获取优化效果分析失败:', error)
      ElMessage.error('获取优化效果分析失败')
    }
  }

  // 获取设备性能趋势
  const fetchDevicePerformanceTrend = async (deviceId, days = 30) => {
    try {
      const response = await getDevicePerformanceTrend(deviceId, days)
      if (response.code === 200) {
        devicePerformanceTrend.value = response.data
      }
    } catch (error) {
      console.error('获取设备性能趋势失败:', error)
      ElMessage.error('获取设备性能趋势失败')
    }
  }

  // 获取任务类型分布
  const fetchTaskTypeDistribution = async () => {
    try {
      const response = await getTaskTypeDistribution()
      if (response.code === 200) {
        taskTypeDistribution.value = response.data
      }
    } catch (error) {
      console.error('获取任务类型分布失败:', error)
      ElMessage.error('获取任务类型分布失败')
    }
  }

  // 获取优化成功率统计
  const fetchOptimizationSuccessRate = async () => {
    try {
      const response = await getOptimizationSuccessRate()
      if (response.code === 200) {
        optimizationSuccessRate.value = response.data
      }
    } catch (error) {
      console.error('获取优化成功率统计失败:', error)
      ElMessage.error('获取优化成功率统计失败')
    }
  }

  // 获取网络拓扑结构
  const fetchNetworkTopology = async () => {
    try {
      const response = await getNetworkTopology()
      if (response.code === 200) {
        networkTopology.value = response.data
      }
    } catch (error) {
      console.error('获取网络拓扑结构失败:', error)
      ElMessage.error('获取网络拓扑结构失败')
    }
  }

  // 搜索
  const handleSearch = () => {
    loading.value = true
    Promise.all([
      fetchSignalQualityAnalysis(),
      fetchOptimizationEffectAnalysis()
    ]).finally(() => {
      loading.value = false
    })
  }

  // 重置搜索条件
  const handleReset = () => {
    Object.assign(queryParams, {
      startTime: '',
      endTime: '',
      deviceType: '',
      taskType: ''
    })
    handleSearch()
  }

  // 刷新所有数据
  const refreshAllData = async () => {
    loading.value = true
    try {
      await Promise.all([
        fetchOverview(),
        fetchDeviceTypeDistribution(),
        fetchDeviceStatusStats(),
        fetchSignalQualityAnalysis(),
        fetchTaskExecutionStats(),
        fetchOptimizationEffectAnalysis(),
        fetchTaskTypeDistribution(),
        fetchOptimizationSuccessRate(),
        fetchNetworkTopology()
      ])
    } catch (error) {
      console.error('刷新数据失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 初始化数据
  const initData = () => {
    refreshAllData()
  }

  // 组件挂载时加载数据
  onMounted(() => {
    initData()
  })

  // 格式化百分比
  const formatPercent = (value) => {
    return value ? `${(value).toFixed(2)}%` : '0%'
  }

  // 格式化数值
  const formatNumber = (value) => {
    if (value === null || value === undefined) return '--'
    return Number(value).toLocaleString('zh-CN')
  }

  // 获取信号强度等级
  const getSignalStrengthLevel = (strength) => {
    if (strength >= -70) return { label: '优秀', type: 'success' }
    if (strength >= -85) return { label: '良好', type: 'warning' }
    return { label: '较差', type: 'danger' }
  }

  // 获取优化效果等级
  const getOptimizationEffectLevel = (improvementRate) => {
    if (improvementRate > 20) return { label: '显著', type: 'success' }
    if (improvementRate > 5) return { label: '一般', type: 'warning' }
    return { label: '较差', type: 'danger' }
  }

  return {
    // 响应式数据
    loading,
    overviewData,
    deviceTypeDistribution,
    deviceStatusStats,
    signalQualityData,
    taskExecutionStats,
    optimizationEffectData,
    devicePerformanceTrend,
    taskTypeDistribution,
    optimizationSuccessRate,
    networkTopology,
    queryParams,
    
    // 方法
    handleSearch,
    handleReset,
    refreshAllData,
    initData,
    fetchDevicePerformanceTrend,
    formatPercent,
    formatNumber,
    getSignalStrengthLevel,
    getOptimizationEffectLevel
  }
}